package org.jeecg.modules.demo.baseselforder.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.baseselforder.entity.BaseSelfOrder;
import org.jeecg.modules.demo.baseselforder.service.IBaseSelfOrderService;
import org.jeecg.modules.demo.baseselfordercommodity.entity.BaseSelfOrderCommodity;
import org.jeecg.modules.demo.baseselfordercommodity.service.IBaseSelfOrderCommodityService;
import org.jeecg.modules.demo.membermanagement.entity.MemberManagement;
import org.jeecg.modules.demo.membermanagement.service.IMemberManagementService;
import org.jeecg.modules.demo.msgtemplatelist.entity.MsgTemplate;
import org.jeecg.modules.demo.msgtemplatelist.service.IMsgTemplateService;
import org.jeecg.modules.demo.storeinfo.entity.StoreInfo;
import org.jeecg.modules.demo.storeinfo.service.IStoreInfoService;
import org.jeecg.modules.util.HttpUtils;
import org.jeecg.modules.util.RedisUtils;
import org.jeecg.modules.util.ToolsUtils;
import org.jeecg.modules.weixin.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 自提订单
 * @Author: jeecg-boot
 * @Date: 2022-01-27
 * @Version: V1.0
 */
@Api(tags = "自提订单")
@RestController
@RequestMapping("/baseselforder/baseSelfOrder")
@Slf4j
public class BaseSelfOrderController extends JeecgController<BaseSelfOrder, IBaseSelfOrderService> {
    @Autowired
    private IBaseSelfOrderService baseSelfOrderService;
    @Autowired
    private IBaseSelfOrderCommodityService baseSelfOrderCommodityService;
    @Autowired
    private IMemberManagementService memberManagementService;
    @Autowired
    private IStoreInfoService storeInfoService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private IMsgTemplateService msgTemplateListService;

    @GetMapping(value = "/list")
    public Result<?> queryPageList(@RequestParam(name = "memberName", required = false) String memberName,
                                   @RequestParam(name = "orderCode", required = false) String orderCode,
                                   @RequestParam(name = "memberPhone", required = false) String memberPhone,
                                   @RequestParam(name = "startDate", required = false) String startDate,
                                   @RequestParam(name = "endDate", required = false) String endDate,
                                   @RequestParam(name = "status", required = false) String status,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        Page<Map<String, Object>> page = new Page<>(pageNo, pageSize);
        IPage<Map<String, Object>> pageList = null;
        if (status.equals("1")) {
            pageList = baseSelfOrderService.listSelfOrder2(page, storeId, memberName, orderCode, memberPhone, startDate, endDate, status);
        } else {
            pageList = baseSelfOrderService.listSelfOrder2(page, storeId, memberName, orderCode, memberPhone, startDate, endDate, status);
        }
        List<Map<String, Object>> records = pageList.getRecords();
        records.forEach(m -> {
            List<BaseSelfOrderCommodity> commodityList = baseSelfOrderCommodityService.list(new QueryWrapper<BaseSelfOrderCommodity>().eq("order_id", String.valueOf(m.get("id"))));
            List<Map<String, Object>> commodityList1 = commodityList.stream().map(c -> {
                Map<String, Object> m1 = ToolsUtils.objectToMap(c);
                BigDecimal totalPrice = m1.get("totalPrice") == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(m1.get("totalPrice")));
                BigDecimal preferAmount = m1.get("preferAmount") == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(m1.get("preferAmount")));
                m1.put("realPrice", totalPrice.subtract(preferAmount));
                String status1 = String.valueOf(m.get("status"));
                if ("0".equals(status1)) {
                    m1.put("statusName", "未自提");
                } else if ("1".equals(status1)) {
                    m1.put("statusName", "已自提");
                }
                return m1;
            }).collect(Collectors.toList());
            m.put("commodityList", commodityList1);
        });
        return Result.OK(pageList);
    }

    @PutMapping(value = "/pickUp")
    public Result<?> pickUp(@RequestParam("id") String id) {

        BaseSelfOrder bso = baseSelfOrderService.getById(id);
        if (!"1".equals(bso.getOrderStatus())) {
            return Result.error("当前订单状态不可自提");
        }
        if (!"0".equals(bso.getStatus())) {
            return Result.error("商品已自提或已退款");
        }
        bso.setStatus("1");
        bso.setPickUpTime(new Date());
        baseSelfOrderService.updateById(bso);

        // 模板消息
        try {
            MemberManagement mm = memberManagementService.getById(bso.getMemberId());
            String gzhOpenId = mm.getGzhOpenId();
            if (gzhOpenId == null) {
                log.info("发送自提成功模板推送失败，会员未绑定公众号");
            } else {
                StoreInfo store = storeInfoService.getById(bso.getStoreId());
                String bossGzhOpenId = storeInfoService.getBossGzhOpenId(bso.getStoreId());
                if (store == null) {
                    log.info("发送自提成功模板推送失败，未查到店铺信息");
                } else {
                    String gzhAppId = store.getGzhAppId();
                    String gzhAppSecret = store.getGzhAppSecret();
                    if (StringUtils.isEmpty(gzhAppId) || StringUtils.isEmpty(gzhAppSecret)) {
                        log.info("发送自提成功模板推送失败，店铺未绑定公众号");
                    } else {
                        String url1 = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + gzhAppId + "&secret=" + gzhAppSecret;
                        String result1 = HttpUtils.sendGet(url1);
                        JSONObject resultJson1 = JSON.parseObject(result1);
                        String errcode = resultJson1.getString("errcode");
                        if (errcode != null && !"0".equals(errcode)) {
                            log.info("发送自提成功模板推送失败，获取accessToken返回值异常，错误码：{}", errcode);
                        } else {
                            String accessToken = resultJson1.getString("access_token");
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日 HH:mm");
                            MsgTemplate msgTemplate = msgTemplateListService.getByTitle("订单核销成功提醒", store.getId());
                            String templateId = msgTemplate.getTemplateId();
                            util.orderWriteoffNotice(templateId, gzhOpenId, bso.getOrderCode(), "", bso.getStoreName(), sdf.format(new Date()), store.getXcxAppId(), "shop/goods/pay?active=1", accessToken);

                            log.info("发送自提成功模板推送成功");
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("发送自提成功模板推送失败，发生异常", e);
        }
        return Result.OK("自提成功");
    }
}











